package com.yuven.appframework.util

import com.chad.library.adapter.base.BaseQuickAdapter
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import android.content.Context
import android.graphics.Canvas
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration
import com.yuven.appframework.R
import com.yuven.appframework.util.span.DslSpannableStringBuilder
import com.yuven.appframework.util.span.DslSpannableStringBuilderImpl
import com.yuven.appframework.widget.CustomLoadMoreView
import com.yuven.baselib.utils.Logger
import com.yuven.baselib.utils.NetHelper
import com.yuven.baselib.utils.ResourceUtil
import com.yuven.baselib.utils.ViewUtils
import com.hjq.toast.ToastUtils
import com.tbruyelle.rxpermissions2.RxPermissions

fun Disposable.addToDisposable(cd: CompositeDisposable) {
    cd.add(this)
}

//BaseQuickAdapter添加状态视图
fun BaseQuickAdapter<*, *>.attachStatusView(context: Context) {
    apply {
        val view = LayoutInflater.from(context)
            .inflate(R.layout.layout_base_quick_adapter_status_view, null)
        view.layoutParams = ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT
        )
        val llEmpty = view.findViewById<ConstraintLayout>(R.id.llEmpty)
        val loading = view.findViewById<ProgressBar>(R.id.loading)
        llEmpty.visibility = View.GONE
        loading.visibility = View.GONE
        setEmptyView(view)

        loadMoreModule.loadMoreView = CustomLoadMoreView()
    }
}

fun BaseQuickAdapter<*, *>.showLoading() {
    emptyLayout?.let {
        val view = (it).getChildAt(0)
        val llEmpty = view.findViewById<ConstraintLayout>(R.id.llEmpty)
        val loading = view.findViewById<ProgressBar>(R.id.loading)
        llEmpty.visibility = View.GONE
        loading.visibility = View.VISIBLE

        data.clear()
        notifyDataSetChanged()
    }
}

/**
 * 当前是否是自定义status view中loading状态(refresh状态)
 * 父类中的isLoading代表的是 load more状态中的loading
 */
fun BaseQuickAdapter<*, *>.isLoadingStatus(): Boolean {
    emptyLayout?.let {
        val view = (it).getChildAt(0)
        val loading = view.findViewById<ProgressBar>(R.id.loading)
        return data.isNullOrEmpty() && loading.visibility == View.VISIBLE
    }
    return false
}

fun BaseQuickAdapter<*, *>.showEmpty(
    imgResId: Int,
    desc: String,
    btnText: String = "",
    bgColor: Int = 0,
    btnClickListener: View.OnClickListener? = null
) {
    emptyLayout?.let {
        val view = (it).getChildAt(0)
        val llEmpty = view.findViewById<ConstraintLayout>(R.id.llEmpty)
        val imgEmpty = view.findViewById<ImageView>(R.id.imgEmpty)
        val tvEmpty = view.findViewById<TextView>(R.id.tvEmpty)
        val btnEmpty = view.findViewById<Button>(R.id.btnEmpty)
        val loading = view.findViewById<ProgressBar>(R.id.loading)

        if (bgColor != 0) {
            llEmpty.setBackgroundColor(bgColor)
        }

        llEmpty.visibility = View.VISIBLE
        loading.visibility = View.GONE

        imgEmpty.setImageResource(imgResId)
        tvEmpty.text = desc
        btnEmpty.visibility = if (btnText.isEmpty()) {
            View.INVISIBLE
        } else {
            btnEmpty.text = btnText
            btnEmpty.setOnClickListener(btnClickListener)
            View.VISIBLE
        }

        data.clear()
        notifyDataSetChanged()
    }
}

//为 TextView 创建扩展函数，其参数为接口的扩展函数
fun TextView.buildSpannableString(init: DslSpannableStringBuilder.() -> Unit) {
    //具体实现类
    val spanStringBuilderImpl = DslSpannableStringBuilderImpl()
    spanStringBuilderImpl.init()
    movementMethod = LinkMovementMethod.getInstance()
    //通过实现类返回SpannableStringBuilder
    text = spanStringBuilderImpl.build()
}

//RecyclerView的Item中间添加横线
fun RecyclerView.addDividerDecoration(leftDp: Float) {
    this.addItemDecoration(object : ItemDecoration(){
        override fun onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
            val divider = ContextCompat.getDrawable(context, R.drawable.appframework_divider_recyclerview)
            val left: Int = ViewUtils.dip2px(leftDp)
            val right = parent.width - left
            val childCount = parent.childCount
            for (i in 0 until childCount - 1) {
                val child = parent.getChildAt(i)
                val params = child.layoutParams as RecyclerView.LayoutParams
                val top = child.bottom + params.bottomMargin
                val bottom = top + (divider?.intrinsicHeight ?: 0)
                divider?.setBounds(left, top, right, bottom)
                divider?.draw(c)
            }
        }
    })
}

fun CheckBox.checkPrivacy(success: () -> Unit, failed: () -> Unit) {
    if (isChecked) {
        success.invoke()
    } else {
        failed.invoke()
    }
}

fun View.setNetWorkCheckClickListener(
    msg: String? = null,
    @androidx.annotation.Nullable l: View.OnClickListener
) {
    setOnClickListener {
        isClickable = false
        if (!NetHelper.isNetAvailable()) {
            if (!TextUtils.isEmpty(msg)) {
                ToastUtils.show(msg)
            } else {
                ToastUtils.show(ResourceUtil.getString(R.string.common_network_not_available))
            }
        } else {
            l.onClick(it)
        }
        //reset
        postDelayed({
            isClickable = true
        }, 1000)
    }
}

fun View.setOnSingleClickListener(
    @androidx.annotation.Nullable l: View.OnClickListener,
    delayMillis: Long = 1000
) {
    setOnClickListener {
        isClickable = false
        l.onClick(it)
        //reset
        postDelayed({
            isClickable = true
        }, delayMillis)
    }
}

inline fun View.setOnSingleClickListener(
    delayMillis: Long = 1000,
    crossinline onClick: (v: View) -> Unit
) {
    setOnClickListener {
        Logger.i("setOnSingleClickListener view.setClickable=false,viewId=${it.id}")
        isClickable = false
        onClick.invoke(it)
        Logger.i("setOnSingleClickListener onClick.invoke viewId=${it.id}")

        //reset
        postDelayed({
            isClickable = true
            Logger.i("setOnSingleClickListener view.setClickable=true,viewId=${it.id}")
        }, delayMillis)
    }
}

/**
 * 权限是否已授权
 */
fun RxPermissions.isGrantedAll(permissions:Array<out String>):Boolean{
    this.apply {
        var isGranted = false
        for (permission in permissions) {
            if(!isGranted(permission)){
                isGranted = false
                break
            }else{
                isGranted  = true
            }
        }
        return isGranted
    }

}
